package com.starblink.store.view

import android.app.Activity
import android.view.View
import com.starblink.android.basic.adapter.BaseBindingVH
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.margin
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.sensorsdata.extension.businessSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler.trackProductOfferMap
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.post.CommonMutateManage.subscribeOrNotMerchant
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.basic.util.CommUtils
import com.starblink.rocketreserver.fragment.BrotherOfferF
import com.starblink.store.databinding.ItemCompareProductViewBinding
import kotlinx.coroutines.MainScope

class ItemCompareProductView(
    binding: ItemCompareProductViewBinding,
    val context: Activity,
    val trackPage: Int = SpmPageDef.StoresComparedBottomSheet, // 埋点：页面追踪
    val searchTerm: String = "", // 埋点：搜索关键词
) :
    BaseBindingVH<BrotherOfferF, ItemCompareProductViewBinding>(binding = binding) {

    override fun onBind(model: BrotherOfferF, position: Int) {
        binding.ivStore.load(model.merchantWeb?.logo, model.merchantWeb?.merchantName)
        binding.title.text = model.merchantWeb?.merchantName ?: ""
        model.klarnaPayFlag?.let { binding.ivKlarna.visibleOrGone(it) {} }
        if (model.minimumPriceFlag != null && model.minimumPriceFlag == true) {
            binding.ivLowest.visibleOrGone(true) {}
            binding.ivDiscount.visibleOrGone(false)
        } else {
            binding.ivLowest.visibleOrGone(false) {}
            //lowest标签优先discount标签
            binding.ivDiscount.visibleOrGone( model.disCountInfo?.discountPercent?.isNotEmpty() == true) {
                text= "Save ${model.disCountInfo?.discountPercent}"
            }
        }
        model.price?.let { binding.tvPrice.show(it, model.currency, model.currencySymbol) }
        binding.viewLineFreeShop.visibleOrGone(false)
        model.logistics?.shippingTag?.let {
            binding.ivFreeShop.visibleOrGone(it.isNotEmpty()) {
                binding.ivFreeShop.text = model.logistics?.shippingTag
                    ?: CommUtils.getString(com.starblink.basic.style.R.string.Free_shipping)
                binding.viewLineFreeShop.visibleOrGone(model.klarnaPayFlag == true)
            }
        }
        binding.tvCur.visibleOrGone(position <= 1) {}
        if (position == 0) {
            binding.tvCur.text = "Current store"
        } else if (position == 1) {
            binding.tvCur.text = "Sold in other stores"
        }

        model.merchantWeb?.let { updateFollow(it.subOrNot) }

        itemView.trackData(
            page = SpmPageDef.StoresComparedBottomSheet,
            element = SpmElementDef.ELE_33032, params = mapOf(
                "merchantName" to "${model.merchantWeb?.merchantName}",
            ),
            businessSuffixID = businessSuffixId(model)
        )

        binding.tvBuy.toProductLink(model, position)
        binding.tvPrice.toProductLink(model, position)
        binding.ivLowest.toProductLink(model, position)

        binding.ivStore.toStoreHome(model, position)
        binding.title.toStoreHome(model, position)
        binding.ivKlarna.toStoreHome(model, position)

        binding.ivFollowed.run {
            click {
                model.merchantWeb?.let { it1 ->
                    subscribeOrNotMerchant(
                        context,
                        merchantId = it1.id,
                        merchantName = it1.merchantName ?: "",
                        subOrNot = it1.subOrNot,
                        scope = MainScope(),
                        refreshState = {
//                            updateFollow(!it1.subOrNot)
                        },
                        resultCallback = {
                            if (it) {
                                ApolloValSetExt.setApolloVal<BrotherOfferF.MerchantWeb>(
                                    it1,
                                    "subOrNot",
                                    it1.subOrNot.not()
                                )
                                SpmTrackHandler.addSingleTrackData(
                                    SkAntEntity(
                                        spmCnt = GTrackerAssistUtils.fetchElementValue(
                                            trackPage,
                                            SpmElementDef.StoreSub
                                        ),
                                        params = trackProductOfferMap(position, model)
                                            .plus("result" to if (model.merchantWeb?.subOrNot == true) "1" else "0")
                                            .plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
                                    )
                                )
                                updateFollow(it1.subOrNot)
                            }
                        }
                    )
                }
            }
        }
    }

    private fun View.toStoreHome(model: BrotherOfferF, position: Int) {//跳转店铺主页
        trackData(
            page = trackPage,
            element = SpmElementDef.ELE_33032,
            params = trackProductOfferMap(position, model),
            onlyHit = true
        )
        click {
            model.merchantWeb?.let {
                CommonRoute.startStoreDetail(context, it.id)
            }
        }
    }

    private fun View.toProductLink(product: BrotherOfferF, position: Int) {//跳转商品外链
        trackData(
            page = trackPage,
            element = SpmElementDef.ProductDetailNewBodyBuy,
            onlyHit = true,
            params = trackProductOfferMap(position, product)
                .plus("searchTerm" to "$searchTerm")
        )
        click {
            product.id?.let { it1 ->
                product.merchantWeb?.let {
                    CommonRoute.startProductLink(
                        context,
                        product.url,
                        it1,
                        productId = product.productId ?: "",
                        product.standardSpuIds ?: "",
                        product.collected == true,
                        product.type,
                        it.id,
                        it.merchantName ?: "",
                        it.logo,
                        it.subOrNot,
                        product.affInfo?.link
                    )
                }
            }
        }
    }

    private fun updateFollow(followed: Boolean) {
        binding.ivFollowed.setImageResource(followed.let {
            if (it) com.starblink.android.common.R.mipmap.icon_web_followed else com.starblink.android.common.R.mipmap.icon_web_follow
        })
    }
}